package com.zjitc.controller;

import com.zjitc.common.ServerResponse;
import com.zjitc.model.User;
import com.zjitc.service.UserService;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

/**
 * Created by LWW on 2018/3/29.
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

  /**
   *用户登录
   */
  @RequestMapping("/login")
    @ResponseBody
    public ServerResponse login(
            @RequestParam(name = "username",required = false) String username,
            @RequestParam(name = "password",required = false) String password,
            HttpSession session) {
        // userService
        // if success -> ServerResponse<User>
        // if error   -> ServerResponse.message = 密码错误
        ServerResponse<User> response = userService.login(username, password);
        if (response.success()) {
            // save to session
            session.setAttribute("user", response.getData());
        }

        return response;
    }

  /**
   * 用户注册
   * @param user
   * @return
   */
    @RequestMapping("/register")
    @ResponseBody
    public ServerResponse register(User user){
      user.setRole(1);
      user.setCreateTime(new Date());
      user.setUpdateTime(new Date());
      ServerResponse<User> response=userService.register(user);
      return response;
    }

  /**
   * 检查用户名是否有效
   */
  @RequestMapping("/check_valid")
  @ResponseBody
  public ServerResponse check(
      @RequestParam(name = "str",required = false)String str,
      @RequestParam(name = "type",required = false)String type
  ){
    ServerResponse<User> response=userService.check(str,type);
    return response;
  }

  /**
   * 获取用户登录信息
   */
  @RequestMapping("/get_user_info")
  @ResponseBody
  public ServerResponse findAll(HttpSession session){
    ServerResponse<User> response=userService.findAllUser(session);
    return response;
  }


  /**
   * 忘记密码
   */
  @RequestMapping("/forget_get_question")
  @ResponseBody
  public ServerResponse forget(User user){
    ServerResponse<User> response=userService.forget(user);
    return response;
  }

  /**
   * 提交问题答案
   */
  @RequestMapping("/forget_check_answer")
  @ResponseBody
  public ServerResponse forgetanswer(User user){
     return null;
  }
}
